package com.message.factory;

import com.constant.MessageType;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.message.Message;
import com.message.RpcReqMessage;
import com.message.RpcRespMessage;

import java.nio.charset.StandardCharsets;

/**
 * @author 罗俊华
 * @date 2021/9/1 - 4:53 下午
 */
public class RpcMessageFactory implements MessageDeSerializerAbstractFactory {

    private final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    {
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
    }

    @Override
    public Message readMessage(byte[] bytesJsonStr, byte messageType) {

        String json = new String(bytesJsonStr, StandardCharsets.UTF_8);

        try {

            switch (messageType) {
                case MessageType.RPC_MESSAGE_REQ:
                    return OBJECT_MAPPER.readValue(json, RpcReqMessage.class);
                case MessageType.RPC_MESSAGE_RESP:
                    return OBJECT_MAPPER.readValue(json, RpcRespMessage.class);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
